#Author: Tanyong
# *-* coding:utf8 *-*
# @time       : 18-7-20 上午8:52
# @Author     : Tanyong
# @Site       : 
# @File       : views.py
# @Software   : PyCharm
import random
import re

from flask import current_app
from flask import make_response
from flask import request, jsonify

from info import redis_store
from info.constants import IMAGE_CODE_REDIS_EXPIRES, SMS_CODE_REDIS_EXPIRES
from info.libs.yuntongxun.sms import CCP
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import passport_blu

@passport_blu.route('/image_code')
def image_code():
    """生成图片验证码"""
    image_code_id = request.args.get('code_id')
    if not image_code_id:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    name, text, image = captcha.generate_captcha()
    print(text)
    try:
        redis_store.set('ImageCodeId_' + image_code_id, text, IMAGE_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logging.error(e)
        print(e)
        return jsonify(errno=RET.DBERR, errmsg='redis数据库存入数据失败')
    response = make_response(image)
    response.headers['Content-Type'] = 'image/jpg'
    return response


@passport_blu.route('/sms_code', methods=['POST'])
def sms_code():
    """生成短信验证码"""

    params_dict = request.json
    mobile = params_dict.get('mobile')
    image_code = params_dict.get('image_code')
    image_code_id = params_dict.get('image_code_id')

    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')
    if not re.match("^1[3578][0-9]{9}$", mobile):
        return jsonify(errno=RET.DATAERR, errmsg='手机号码错误')

    real_image_code = redis_store.get('ImageCodeId_' + image_code_id)

    if real_image_code != image_code:
        return jsonify(errno=RET.DATAERR, errmsg="图片验证码错误")
    sms_code = '%06d' % random.randint(0, 999999)
    current_app.logging.debug(sms_code)
    result = CCP().send_template_sms(mobile, [sms_code, SMS_CODE_REDIS_EXPIRES/60], 1)
    if result != 0:
        return jsonify(errno=RET.THIRDERR, errmsg="短信验证码发送失败")

    return jsonify(errno=RET.OK, errmsg="短信验证码发送成功")




